import React, { useCallback, useRef, useState } from 'react';
import { Button, Descriptions, Drawer, message, Popconfirm, Space, Upload } from 'antd';
import { ProTable, ProColumns, ProForm, ProFormText, ProFormItem, ProFormGroup } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { fetchInvoiceList, deleteInvoice, downloadInvoice,updateInvoice, finishInvoice,fetchInvoiceDetail } from '@/services/ant-design-pro/invoice';
import type { ActionType } from '@ant-design/pro-components';
import FileUpload from '@/components/FileUpload';
import FormItem from 'antd/es/form/FormItem';

const InvoiceList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<any | undefined>(undefined);
  const [form] = ProForm.useForm();
  const [activeKey, setActiveKey] = useState<string>('');
  const { run: delRun, loading: deleteLoading } = useRequest(deleteInvoice, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('删除成功');
    },
    onError: () => {
      message.error('删除失败，请重试');
    },
  });

  const handleRemove = useCallback(
    async (selectedRows: any[]) => {
      if (selectedRows.length === 0) {
        message.warning('请先选择要删除的项');
        return;
      }
      await delRun({ id: selectedRows.map((row) => row.id)[0] });
    },
    [delRun],
  );

  const showDeatil = async (record: any)=> {
    const deatil = await fetchInvoiceDetail(record.id)
    setCurrentRecord(deatil?.data);
    form.setFieldsValue(record);
    setDrawerVisible(true);
  }
  

  const columns: ProColumns<any>[] = [
    {
      title: '订单编号',
      dataIndex: 'orderCode',
      width: 150,
      ellipsis: true,
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      width: 100,
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: 120,
      ellipsis: true,
    },
    {
      title: '发票状态',
      dataIndex: 'billStatus',
      search: false,
      width: 100,
      ellipsis: true,
      valueEnum: {
        0: {text: '待开'},
        1: {text: '已开'},
      }
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      width: 100,
      ellipsis: true,
      valueEnum: {
        0: '支付宝',
        1: '微信',
        2: '对公支付',
      },
    },
    
    {
      title: '实付金额',
      dataIndex: 'payAmount',
      width: 100,
      ellipsis: true,
    },
    {
      title: '订单名称',
      dataIndex: 'orderName',
      width: 150,
      search: false,
      ellipsis: true,
    },
   

 

    {
      title: '操作',
      width: 100,
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            showDeatil(record);
        
          }}
        >
          查看
        </a>
        // <Popconfirm
        //   key="delete"
        //   title="确定删除吗？"
        //   onConfirm={() => handleRemove([record])}
        //   okText="确定"
        //   cancelText="取消"
        // >
        //   <a>删除</a>
        // </Popconfirm>,
        // <a
        //   key="download"
        //   onClick={() => downloadInvoice(record.id)}
        // >
        //   下载发票
        // </a>,
      ],
    },
  ];

  return (
    <>
      <ProTable<any>
        scroll={{ x: 1300 }}
        headerTitle="发票管理列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        request={(params) => fetchInvoiceList({...params,'billStatus':activeKey})}
        columns={columns}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: "", label: <span>全部</span> },
              { key: "0", label: <span>待开</span> },
              { key: "1", label: <span>已开</span> },
              // { key: "0", label: <span>未开</span> },
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
      />

      <Drawer
        title="发票详情"
        width={700}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>关闭</Button>
            <Popconfirm
        key="sub"
        title="确认发票已经开具完毕么"
        onConfirm={async () => {
          await form?.submit?.()
          actionRef.current?.reload();
        }}
      >
            <Button key="submit" type="primary">确认提交</Button>
            </Popconfirm>
          </Space>
        }
      >
        <ProForm form={form} layout="inline" initialValues={currentRecord}
        onFinish={ async (values) => {
         await updateInvoice({...currentRecord,billUrl:values.billUrl})
         await finishInvoice({id:currentRecord.id,billUrl:values.billUrl})
         console.log(values)
         form.resetFields()
          setDrawerVisible(false)
        }}
        submitter={false}>
  <Descriptions  title="用户信息"  style={{ marginTop: 24 }} layout="vertical">

    <Descriptions.Item label="用户名称">{currentRecord?.userName || '-'}</Descriptions.Item>
    <Descriptions.Item label="用户编码">{currentRecord?.userCode || '-'}</Descriptions.Item>
    <Descriptions.Item label="手机号">{currentRecord?.userMobile || '-'}</Descriptions.Item>
    <Descriptions.Item label="用户类型">{currentRecord?.userType ==0 ? '个人' : '企业' || '-'}</Descriptions.Item>
    <Descriptions.Item label="用户邮箱">{currentRecord?.userEmail || '-'}</Descriptions.Item>
  </Descriptions>

  <Descriptions title="订单信息"  style={{ marginTop: 24 }} layout="vertical">
    <Descriptions.Item label="订单编号">{currentRecord?.orderCode || '-'}</Descriptions.Item>
    <Descriptions.Item label="订单名称">{currentRecord?.orderName || '-'}</Descriptions.Item>
    <Descriptions.Item label="实付金额">{currentRecord?.payAmount || '-'}</Descriptions.Item>
    <Descriptions.Item label="支付方式">{currentRecord?.payType == 0 ? '支付宝' :
      currentRecord?.payType == 1 ? '微信' :
      currentRecord?.payType == 2 ? '对公支付' : '对公支付'}</Descriptions.Item>
    <Descriptions.Item label="发票状态">{
      currentRecord?.billStatus === 0 ? '待开' :
      currentRecord?.billStatus === 1 ? '已开'  : '-'
    }</Descriptions.Item>
    <Descriptions.Item label="发票编码">{currentRecord?.billCode || '-'}</Descriptions.Item>
    {/* <Descriptions.Item label="重开原因">{currentRecord?.reason || '-'}</Descriptions.Item>
    <Descriptions.Item label="备注">{currentRecord?.remark || '-'}</Descriptions.Item> */}
    <Descriptions.Item label="创建时间">{currentRecord?.createTime || '-'}</Descriptions.Item>
  </Descriptions>

  <Descriptions title="发票抬头信息"  style={{ marginTop: 24 }} layout="vertical">
  <Descriptions.Item label="发票类型">{currentRecord?.billType == 0 ? '增值税专用发票' : '增值税普通电子发票' || '-'}</Descriptions.Item> 
  <Descriptions.Item label="企业名称">{currentRecord?.companyName || '-'}</Descriptions.Item>
    {/* <Descriptions.Item label="企业名称">{currentRecord?.companyName || '-'}</Descriptions.Item> */}
    <Descriptions.Item label="纳税人识别号">{currentRecord?.taxNumber || '-'}</Descriptions.Item>
    <Descriptions.Item label="银行名称">{currentRecord?.bankName || '-'}</Descriptions.Item>
    <Descriptions.Item label="银行账号">{currentRecord?.bankAccount || '-'}</Descriptions.Item>

    <Descriptions.Item label="手机号">{currentRecord?.mobile || '-'}</Descriptions.Item>
    <Descriptions.Item label="收件人邮箱">{currentRecord?.email || '-'}</Descriptions.Item>
    <Descriptions.Item label="注册地址">{currentRecord?.registerAddress || '-'}</Descriptions.Item>
    <Descriptions.Item label="注册电话">{currentRecord?.registerMobile || '-'}</Descriptions.Item>
    <Descriptions.Item label="所在地址">{currentRecord?.addressName || '-'}</Descriptions.Item>
    <Descriptions.Item label="详细地址">{currentRecord?.addressDetail || '-'}</Descriptions.Item>
    <Descriptions.Item label="发票申请时间">{currentRecord?.createTime || '-'}</Descriptions.Item>
  </Descriptions>




      <Descriptions title="发票文件" bordered style={{ marginTop: 24 }} layout="vertical">
        <Descriptions.Item label="上传发票附件">
          <FormItem name="billUrl" rules={[{ required: true, message: '请上传发票附件' }]}>
          <FileUpload value={form.getFieldValue('billUrl')} onChange={(url) => form.setFieldsValue({ attachment: url,billUrl: url })} />
          </FormItem>
        </Descriptions.Item>
      </Descriptions>
        
        </ProForm>
      </Drawer>
    </>
  );
};

export default InvoiceList;

